<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\MoneyBook;
use App\Models\MoneyBookUser;
use App\Models\MoneyCategory;
use App\Models\MoneySubCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * 显示注册表单
     */
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    /**
     * 显示登录表单
     */
    public function showLoginForm(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        return view('auth.login')->with(['is_wechat' => strpos($userAgent, 'MicroMessenger') !== false]);
    }

    /**
     * 处理用户注册
     */
    public function register(Request $request)
    {
        try {
            // 验证请求数据
            $request->validate([
                'name' => 'required|string|min:2|max:255|unique:users,name',
                'password' => 'required|string|min:6|confirmed',
            ], [
                'name.required' => '用户名不能为空',
                'name.min' => '用户名至少2个字符',
                'name.max' => '用户名不能超过255个字符',
                'name.unique' => '该用户名已被注册',
                'password.required' => '密码不能为空',
                'password.min' => '密码至少6位',
                'password.confirmed' => '两次输入的密码不一致',
            ]);

            // 创建用户
            $user = User::create([
                'name' => $request->name,
                'nickname' => $request->name,
                'email' => $request->name . '@local.com', // 生成一个本地邮箱
                'password' => Hash::make($request->password),
                'email_verified_at' => now(), // 直接标记为已验证
            ]);

            // 为新用户创建默认账本
            $book = $user->createDefaultBookForUser();

            return response()->json([
                'success' => true,
                'message' => '注册成功！',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                ]
            ]);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            \Log::error('注册失败: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => '注册失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 处理用户登录
     */
    public function login(Request $request)
    {
        try {
            // 验证请求数据
            $request->validate([
                'name' => 'required|string',
                'password' => 'required|string',
            ], [
                'name.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
            ]);

            // 尝试登录（使用用户名）
            $credentials = [
                'name' => $request->name,
                'password' => $request->password
            ];

            if (Auth::attempt($credentials, $request->boolean('remember'))) {
                $request->session()->regenerate();

                $user = Auth::user();

                return response()->json([
                    'success' => true,
                    'message' => '登录成功！',
                    'user' => [
                        'id' => $user->id,
                        'name' => $user->name,
                    ],
                    'redirect_to' => session()->pull('url.intended', route('home'))
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => '用户名或密码错误'
            ], 500);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            \Log::error('登录失败: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => '登录失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 处理用户登出
     */
    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => '已退出登录',
                'redirect' => route('login')
            ]);
        }

        return redirect()->route('login');
    }

    /**
     * 创建默认分类和子分类
     */
    private function createDefaultCategories($bookId)
    {
        try {
            // 从JSON文件读取默认分类数据
            $jsonPath = storage_path('app/default_categories.json');

            if (!file_exists($jsonPath)) {
                \Log::error('默认分类JSON文件不存在: ' . $jsonPath);
                return;
            }

            $jsonContent = file_get_contents($jsonPath);
            $defaultData = json_decode($jsonContent, true);

            if (!$defaultData || !isset($defaultData['categories'])) {
                \Log::error('默认分类JSON文件格式错误');
                return;
            }

            // 遍历所有分类
            foreach ($defaultData['categories'] as $categoryData) {
                // 创建主分类
                $category = MoneyCategory::create([
                    'book_id' => $bookId,
                    'name' => $categoryData['name'],
                    'icon' => $categoryData['icon'],
                    'type' => $categoryData['type'],
                    'sort' => $categoryData['sort'],
                    'description' => $categoryData['description'] ?? null,
                ]);

                // 创建子分类
                if (isset($categoryData['sub_categories']) && is_array($categoryData['sub_categories'])) {
                    foreach ($categoryData['sub_categories'] as $subCategoryData) {
                        MoneySubCategory::create([
                            'book_id' => $bookId,
                            'category_id' => $category->id,
                            'name' => $subCategoryData['name'],
                            'icon' => $subCategoryData['icon'],
                            'sort' => $subCategoryData['sort'],
                            'description' => $subCategoryData['description'] ?? null,
                        ]);
                    }
                }
            }

        } catch (\Exception $e) {
            \Log::error('创建默认分类失败: ' . $e->getMessage());
            // 如果JSON文件读取失败，可以选择创建基础分类或者抛出异常
            throw new \Exception('创建默认分类失败');
        }
    }
}
